<template>
  <div class="home-container">
    <!-- 侧边导航栏 -->
    <el-aside width="240px" class="sidebar">
      <div class="logo">
        <span class="logo-text">智周万物</span>
      </div>
      <el-menu
        default-active="1"
        class="sidebar-menu"
        background-color="#f5f7fa"
        text-color="#333"
        active-text-color="#039be5"
        router
      >
        <el-menu-item @click="startChat('new-chat')">
          <el-icon><Plus /></el-icon>
          <span>新建聊天</span>
        </el-menu-item>
        <el-menu-item index="/">
          <el-icon><Home /></el-icon>
          <span>AI聊天</span>
        </el-menu-item>
        <el-menu-item index="/history">
          <el-icon><History /></el-icon>
          <span>历史记录</span>
        </el-menu-item>
        <el-menu-item index="/profile">
          <el-icon><User /></el-icon>
          <span>个人中心</span>
        </el-menu-item>
      </el-menu>
    </el-aside>

    <!-- 主内容区 -->
    <el-main class="main-content">
      <div class="header-actions">
        <el-dropdown @command="handleUserCommand">
          <div class="user-info" style="cursor: pointer;">
            <el-avatar class="user-avatar">
              <img src="https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png" alt="用户头像">
            </el-avatar>
            <span class="username">{{ userInfo.username }}</span>
          </div>
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item command="profile">查看个人信息</el-dropdown-item>
              <el-dropdown-item command="switch">更换账号</el-dropdown-item>
              <el-dropdown-item command="logout">退出登录</el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>

        <!-- 账号信息弹窗 -->
        <el-dialog v-model="dialogVisible" title="账号信息" width="30%">
          <div class="profile-info">
            <div class="profile-avatar">
              <el-avatar size="large">
                <img src="https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png" alt="用户头像">
              </el-avatar>
            </div>
            <div class="profile-details">
              <p><strong>用户名:</strong> {{ userInfo.username }}</p>
              <p><strong>邮箱:</strong> {{ userInfo.email || '未设置' }}</p>
              <p><strong>账号状态:</strong> {{ userInfo.status ? '正常' : '异常' }}</p>
              <p><strong>最后登录:</strong> {{ formatDate(userInfo.lastLogin) || '从未登录' }}</p>
            </div>
          </div>
          <template #footer>
            <el-button @click="dialogVisible = false">关闭</el-button>
          </template>
        </el-dialog>
      </div>

      <div class="welcome-section">
        <h1>您好，欢迎使用智周万物AI系统！</h1>
        <p>我能在你的工作和生活中提供帮助，有什么可以帮您的吗？</p>
      </div>

      <!-- AI功能卡片 -->
      <div class="feature-cards">
        <div class="feature-card" @click="startChat('ai-writing')">
          <div class="card-icon ai-writing-icon"></div>
          <h3>AI创作</h3>
          <div class="card-actions">
            <el-button size="small" type="text">写一首诗赞美祖国</el-button>
            <el-button size="small" type="text">写一篇3年级的小作文300字</el-button>
            <el-button size="small" type="text">帮我出三道小学五年级的数学应用题</el-button>
          </div>
        </div>

        <div class="feature-card" @click="startChat('smart-editing')">
          <div class="card-icon smart-editing-icon"></div>
          <h3>智能编辑</h3>
          <div class="card-actions">
            <el-button size="small" type="text">写一首诗赞美祖国</el-button>
            <el-button size="small" type="text">帮我润色一个活动方案，要求生动、简洁、有吸引力</el-button>
            <el-button size="small" type="text">帮我出三道小学五年级的数学应用题</el-button>
          </div>
        </div>

        <div class="feature-card" @click="startChat('life-assistant')">
          <div class="card-icon life-assistant-icon"></div>
          <h3>工作生活助手</h3>
          <div class="card-actions">
            <el-button size="small" type="text">写一首诗赞美祖国</el-button>
            <el-button size="small" type="text">写一篇3年级的小作文300字</el-button>
            <el-button size="small" type="text">帮我出三道小学五年级的数学应用题</el-button>
          </div>
        </div>
      </div>

      <!-- 快捷操作 -->
      <div class="quick-actions">
        <p class="section-title">试一试新功能</p>
        <div class="action-buttons">
          <el-button type="default" size="small">
            和高考大省状元聊天
          </el-button>
          <el-button type="default" size="small">
            讲讲西游记的故事
          </el-button>
          <el-button type="default" size="small">
            写一个智能的设计方案
          </el-button>
        </div>
      </div>

      <!-- AI聊天输入框 -->
      <div class="chat-input-container">
        <el-input
          v-model="message"
          class="chat-input"
          placeholder="来说点什么吧...(Shift + Enter 换行)"
          :rows="4"
          type="textarea"
          :maxlength="2000"
          show-word-limit
          @keydown.enter.native="handleKeyDown"
        >
          <template #append>
            <el-button type="primary" @click="handleSend"><el-icon><Send /></el-icon></el-button>
          </template>
        </el-input>
      </div>
    </el-main>
  </div>
</template>

<script setup>
import { useRouter } from 'vue-router'
import { Plus, Home, History, User, ArrowRight, Send } from '@element-plus/icons-vue'
import { ElMessage, ElDialog } from 'element-plus'
import { userApi } from '../api/api'
import { ref, onMounted } from 'vue'

const router = useRouter()
const dialogVisible = ref(false)
const userInfo = ref({ username: 'admin', status: true })
const message = ref('')

// 获取用户信息
const getUserInfo = async () => {
  try {
    const res = await userApi.getUserInfo()
    userInfo.value = res.data
  } catch (error) {
    console.error('获取用户信息失败', error)
  }
}

// 格式化日期
const formatDate = (dateString) => {
  if (!dateString) return ''
  const date = new Date(dateString)
  return date.toLocaleString()
}

// 处理用户命令
const handleUserCommand = async (command) => {
  switch (command) {
    case 'profile':
      dialogVisible.value = true
      break
    case 'switch':
      // 清除当前登录状态并跳转到登录页
      localStorage.removeItem('token')
      router.push('/login')
      ElMessage.success('已切换账号')
      break
    case 'logout':
      try {
        await userApi.logout()
      } finally {
        localStorage.removeItem('token')
        router.push('/login')
        ElMessage.success('已退出登录')
      }
      break
  }
}

onMounted(() => {
  getUserInfo()
})

// 生成唯一聊天ID
const generateChatId = () => {
  return Date.now().toString(36) + Math.random().toString(36).substr(2, 5)
}

// 开始新聊天
const startChat = (type, initialMessage = '') => {
  const chatId = generateChatId()
  router.push({ name: 'Chat', params: { id: chatId, type }, query: { initialMessage } })
  ElMessage.success(`已开始${getChatTypeName(type)}聊天`)
}

// 处理发送消息
const handleSend = () => {
  if (!message.value.trim()) return
  startChat('new-chat', message.value)
  message.value = ''
}

// 处理键盘事件
const handleKeyDown = (e) => {
  if (e.key === 'Enter' && !e.shiftKey) {
    e.preventDefault()
    handleSend()
  }
}

// 获取聊天类型名称
const getChatTypeName = (type) => {
  const typeMap = {
    'ai-writing': 'AI创作',
    'smart-editing': '智能编辑',
    'life-assistant': '工作生活助手'
  }
  return typeMap[type] || '新'
}
</script>

<style scoped>
.home-container {
  display: flex;
  height: 100vh;
  overflow: hidden;
}

.sidebar {
  background-color: #f5f7fa;
  border-right: 1px solid #e5e9f2;
  height: 100%;
}

.logo {
  height: 60px;
  display: flex;
  align-items: center;
  justify-content: center;
  border-bottom: 1px solid #e5e9f2;
  padding: 0 20px;
}

.logo-text {
  font-size: 18px;
  font-weight: bold;
  color: #039be5;
}

.sidebar-menu {
  border-right: none;
  height: calc(100% - 60px);
}

.main-content {
  padding: 20px;
  overflow-y: auto;
  background-color: #f9fafc;
}

.header-actions {
  display: flex;
  justify-content: flex-end;
  margin-bottom: 30px;
}

.user-info {
  display: flex;
  align-items: center;
}

.user-avatar {
  width: 40px;
  height: 40px;
  margin-right: 10px;
}

.username {
  font-size: 14px;
  color: #333;
}

.welcome-section {
  margin-bottom: 40px;
  text-align: center;
  padding: 40px 0;
  background-color: #fff;
  border-radius: 12px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.04);
}

.welcome-section h1 {
  font-size: 24px;
  color: #333;
  margin-bottom: 10px;
}

.welcome-section p {
  font-size: 16px;
  color: #666;
}

.feature-cards {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 20px;
  margin-bottom: 40px;
}

.feature-card {
  background-color: #fff;
  border-radius: 12px;
  padding: 20px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.04);
  cursor: pointer;
  transition: transform 0.2s, box-shadow 0.2s;
}

.feature-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.08);
}

.card-icon {
  width: 48px;
  height: 48px;
  border-radius: 8px;
  margin-bottom: 15px;
}

.ai-writing-icon {
  background-color: rgba(63, 81, 181, 0.1);
}

.smart-editing-icon {
  background-color: rgba(76, 175, 80, 0.1);
}

.life-assistant-icon {
  background-color: rgba(255, 152, 0, 0.1);
}

.feature-card h3 {
  font-size: 18px;
  margin-bottom: 15px;
  color: #333;
}

.card-actions {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.quick-actions {
  background-color: #fff;
  border-radius: 12px;
  padding: 20px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.04);
}

.section-title {
  font-size: 16px;
  color: #333;
  margin-bottom: 15px;
  font-weight: 500;
}

.action-buttons {
  display: flex;
  gap: 10px;
  flex-wrap: wrap;
}

.chat-input-container {
  position: fixed;
  bottom: 20px;
  left: calc(240px + 20px);
  right: 20px;
  z-index: 100;
}

.chat-input {
  resize: none;
}
</style>